package com.flyqiu.flow.model.format.flowable;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.Element;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class FlowableProcessFormat extends DefaultFlowableElementFormat {
    @Override
    public String xmlElementType() {
        return "process";
    }

    @Override
    protected void elementToJson(Element element, List<Attribute> unProcessedAttrs, Map<String, Attribute> elementAttrMap, JSONObject result) {
        List<Element> elements = element.elements();
        JSONArray activites = new JSONArray();
        JSONArray sequences = new JSONArray();
        for (Element itemElement : elements) {
            JSONObject item = bpmnFormat.getElementFormat(itemElement.getName()).elementToJson(bpmnFormat, itemElement);
            if (itemElement.getName().equals("sequenceFlow")) {
                sequences.add(item);
            } else {
                activites.add(item);
            }
        }
        result.put("activity", activites);
        result.put("sequences", sequences);
    }

    @Override
    protected void jsonToElement(JSONObject jsonElement, Set<String> unProcessedKeys, Element srcElement) {

        JSONArray activites = jsonElement.getJSONArray("activity");
        for (int i = 0; i < activites.size(); i++) {
            JSONObject activity = activites.getJSONObject(i);
            String elementType = getElementType(activity);
            bpmnFormat.getElementFormat(elementType).jsonToElement(bpmnFormat, activity, srcElement);
        }

        JSONArray sequences = jsonElement.getJSONArray("sequences");
        for (int i = 0; i < sequences.size(); i++) {
            JSONObject activity = sequences.getJSONObject(i);
            DefaultFlowableElementFormat elementFormat = bpmnFormat.getElementFormat(getElementType(activity));
            elementFormat.jsonToElement(bpmnFormat, activity, srcElement);

        }

    }

}
